package com.minivision.sdktestdemo.controler.ui.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.service.MusicService;
import com.minivision.sdktestdemo.ui.MarqueeToolbar;
import com.minivision.sdktestdemo.ui.MusicControlHandler;
import com.minivision.sdktestdemo.ui.view.MusicListPopContentView;
import com.minivision.sdktestdemo.ui.view.PopupView;
import com.minivision.sdktestdemo.utils.CloseUtils;
import com.minivision.sdktestdemo.utils.TextFormatUtils;
import com.npi.blureffect.Blur;
import com.npi.blureffect.ImageUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by devtang on 2016/4/27.
 */
public class MusicPlayControler {
    private static final String DEFAULT_BLURRED_IMG_PATH = Environment.getExternalStorageDirectory() + File.separator + "blurred_image.png";
    @Bind(R.id.tv_start_time)
    TextView mTvStartTime;

    @Bind(R.id.tv_end_time)
    TextView mTvEndTime;

    @Bind(R.id.btn_loop)
    ImageButton mBtnLoop;

    @Bind(R.id.btn_play)
    ImageButton mBtnPlay;

    @Bind(R.id.slider)
    SeekBar mSlider;

    @Bind(R.id.tool_bar)
    MarqueeToolbar mToolBar;

    @Bind(R.id.bigAlbumCover)
    ImageSwitcher mBackGround;

    private MusicMiniPlayControler.PlayListGetter mPlayListGetter;

    private PopupView mPopupWindow;

    private PlayMusicEvent mEvent;
    private Activity mContext;
    private MusicControlHandler.onProgressUpdated mProgressListener;
    private OnChangeOrder mOrderListener;
    private ExecutorService mThreadPool;

    public interface OnChangeOrder {
        public void changeOrder();
    }

    public MusicPlayControler(Activity activity) {
        ButterKnife.bind(this, activity);
        mContext = activity;
        mProgressListener = (MusicControlHandler.onProgressUpdated) activity;
        mOrderListener = (OnChangeOrder) activity;
        mThreadPool = Executors.newSingleThreadExecutor();
        mPlayListGetter = (MusicMiniPlayControler.PlayListGetter) activity;
    }


    @OnClick(R.id.btn_list)
    public void onClickList() {
        if (mPlayListGetter.getPlayList() != null) {
            if (mPopupWindow == null) {
                mPopupWindow = new PopupView(mContext, new MusicListPopContentView(mContext));
            }
            mPopupWindow.show(mPlayListGetter.getPlayList(), mEvent);
        }
    }

    public void setTitle(String title, String subTitle) {
        mToolBar.setTitle(title);
        mToolBar.selectTitle();
        mToolBar.setSubtitle(subTitle);
    }

    public void transformImage(Uri uri, final String tarPath) {
        //将图片转换为模糊图片
        Observable.just(uri)
                .map(new Func1<Uri, Drawable>() {
                    @Override
                    public Drawable call(Uri uri) {
                        InputStream is = null;
                        try {
                            File blurredImage = new File(tarPath);
                            is = mContext.getContentResolver().openInputStream(uri);
                            Bitmap image = BitmapFactory.decodeStream(is);
                            Bitmap newImg = Blur.fastblur(mContext, image, 15);
                            ImageUtils.storeImage(newImg, blurredImage);
                            Drawable drawable = BitmapDrawable.createFromPath(tarPath);
                            return drawable;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } finally {
                            CloseUtils.close(is);
                        }
                        return null;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Drawable>() {
                    @Override
                    public void call(Drawable drawable) {
                        updateBackGround(drawable);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        updateBackGround(null);
                    }
                });

//        mThreadPool.execute(new Runnable() {
//            @Override
//            public void run() {
//                InputStream is = null;
//                try {
//                    is = mContext.getContentResolver().openInputStream(uri);
//                    final Bitmap image = BitmapFactory.decodeStream(is);
//                    Bitmap newImg = Blur.fastblur(mContext, image, 15);
//                    ImageUtils.storeImage(newImg, blurredImage);
//                    final Drawable drawable = BitmapDrawable.createFromPath(tarPath);
//                    if (mEvent.mAlbumUri.equals(uri)) {
//                        mContext.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                updateBackGround(drawable);
//                            }
//                        });
//                    }
//                } catch (FileNotFoundException e) {
//                    mContext.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            updateBackGround(null);
//                        }
//                    });
//                } finally {
//                    CloseUtils.close(is);
//                }
//            }
//        });
    }

    private void updateBackGround(Drawable drawable) {
        final int screenWidth = ImageUtils.getScreenWidth(mContext);
        if (drawable != null) {
            mBackGround.setImageDrawable(drawable);
        } else {
            mBackGround.setImageResource(R.drawable.playpage_background);
        }
    }

    private final ViewSwitcher.ViewFactory BACKGROUND_FACTORY = new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            ImageView imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return imageView;
        }
    };

    public void initImageSwitcher(ImageSwitcher imageSwitcher) {
        imageSwitcher.setFactory(BACKGROUND_FACTORY);
        //设置背景的淡入淡出
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
        alphaAnimation.setDuration(500);
        imageSwitcher.setInAnimation(alphaAnimation);

        alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        alphaAnimation.setDuration(500);
        imageSwitcher.setOutAnimation(alphaAnimation);
    }

    public void init() {
        //初始化imageswitcher
        initImageSwitcher(mBackGround);
        //初始化背景图片
        updateBackGround(null);
        //初始化seekbar样式
        initSeekBar();
        //初始化标题,按钮样式,
//        updateMusicStatus(event);
    }

    public void initSeekBar() {
        mSlider.getThumb().setColorFilter(mContext.getResources().getColor(R.color.textPrimaryColor), PorterDuff.Mode.SRC_IN);
        mSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTvStartTime.setText(TextFormatUtils.getMusicTime(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //拖动前,停止更新进度条
                mProgressListener.stopUpdate();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mEvent.mStatus == PlayMusicEvent.STOP) {
                    update(0, mEvent.mDuration);
                } else {
                    //更新进度条
                    mEvent.mCurPos = seekBar.getProgress();
                    mEvent.mStatus = PlayMusicEvent.SEEK;
                    EventBus.getDefault().post(mEvent);
                    mProgressListener.startUpdate();
                }
            }
        });
    }

    public void updateMusicStatus(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
        //初始化播放按钮
        mBtnPlay.setImageResource(mEvent.mStatus == PlayMusicEvent.PLAY ?
                R.drawable.play_btn_pause :
                R.drawable.play_btn_play);
        //初始化顺序按钮
        mBtnLoop.setImageResource(event.mOrder == MusicService.LOOP ?
                R.drawable.play_icn_one : event.mOrder == MusicService.ALL ?
                R.drawable.play_icn_loop : R.drawable.play_icn_shuffle);
        //初始化标题和副标题
        setTitle(event.mName, event.mSubName);
        transformImage(event.mAlbumUri, DEFAULT_BLURRED_IMG_PATH);
        update(mEvent.mCurPos, mEvent.mDuration);
    }

    public void stopThreadPool() {
        mThreadPool.shutdownNow();
    }

    public void update(int value, int max) {
        if (mEvent.mStatus == PlayMusicEvent.STOP) {
            value = 0;
        }
        //更新进度条
        mSlider.setMax(max);
        mSlider.setProgress(value);
        mTvStartTime.setText(TextFormatUtils.getMusicTime(value));
        mTvEndTime.setText(TextFormatUtils.getMusicTime(max));
    }

    @OnClick(R.id.btn_play)
    public void onClickPlay() {
        switch (mEvent.mStatus) {
            case PlayMusicEvent.STOP:
            case PlayMusicEvent.PAUSE:
                play();
                mProgressListener.startUpdate();
                break;
            case PlayMusicEvent.PLAY:
                pause();
                break;
        }
    }

    @OnClick(R.id.btn_loop)
    public void onChangeOrder() {
        switch (mEvent.mOrder) {
            case MusicService.LOOP:
                mEvent.mOrder = MusicService.RAND;
                mBtnLoop.setImageResource(R.drawable.play_icn_shuffle);
                Toast.makeText(mContext, "随机播放", Toast.LENGTH_SHORT).show();
                break;
            case MusicService.RAND:
                mEvent.mOrder = MusicService.ALL;
                mBtnLoop.setImageResource(R.drawable.play_icn_loop);
                Toast.makeText(mContext, "顺序播放", Toast.LENGTH_SHORT).show();
                break;
            case MusicService.ALL:
                mEvent.mOrder = MusicService.LOOP;
                mBtnLoop.setImageResource(R.drawable.play_icn_one);
                Toast.makeText(mContext, "单曲循环", Toast.LENGTH_SHORT).show();
                break;
        }
        mOrderListener.changeOrder();
    }

    private void play() {
        mEvent.mStatus = PlayMusicEvent.PLAY;
        EventBus.getDefault().post(mEvent);
    }

    public void pause() {
        mEvent.mStatus = PlayMusicEvent.PAUSE;
        EventBus.getDefault().post(mEvent);
    }

    @OnClick(R.id.btn_next)
    public void playNext() {
        mEvent.mStatus = PlayMusicEvent.NEXT;
        EventBus.getDefault().post(mEvent);
    }

    @OnClick(R.id.btn_prev)
    public void playPrev() {
        mEvent.mStatus = PlayMusicEvent.PREV;
        EventBus.getDefault().post(mEvent);
    }
}
